﻿using Microsoft.Win32;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ZhwangTool
{
    /// <summary>
    /// FormulaRemoverUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class FormulaRemoverUserControl : UserControl
    {

        string obFolder = string.Empty;

        public FormulaRemoverUserControl() { InitializeComponent(); }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置文件过滤器，限定为 .xlsx 格式
            openFileDialog.Filter = "Excel 工作簿 (*.xlsx)|*.xlsx";

            // 可选：设置其他常用属性
            openFileDialog.Title = "请选择要修改的Excel文件"; // 对话框标题

            openFileDialog.InitialDirectory = @"C:\";      // 初始目录

            openFileDialog.RestoreDirectory = true;        // 记住上次目录

            openFileDialog.Multiselect = true;

            var result = openFileDialog.ShowDialog();

            if(result == true)
            {
                foreach(string fileName in openFileDialog.FileNames)
                {
                    if(listBox1.Items.Cast<string>().Contains(fileName) == false)
                    {
                        listBox1.Items.Add(fileName);
                    }
                }
            } else
            {
                MessageBox.Show("没有选定有效的文件，点击确定后重试。", "注意！");
            }
        }


        private void Button2_Click(object sender, RoutedEventArgs e) { listBox1.Items.Clear(); }

        private bool IsXlsxFile(string filePath)
        { return System.IO.Path.GetExtension(filePath)?.Equals(".xlsx", StringComparison.OrdinalIgnoreCase) == true; }

        private void AddUniqueItem(ListBox listBox, string value)
        {
            if(!listBox.Items.Cast<string>().Any(x => x.Equals(value, StringComparison.OrdinalIgnoreCase)))
            {
                listBox.Items.Add(value);
            }
        }

        private void ListBox1_DragEnter(object sender, DragEventArgs e)
        {
            if(e.Data.GetDataPresent(DataFormats.FileDrop))
                //e.Effect = DragDropEffects.All;    //重要代码：表明是所有类型的数据，比如文件路径

                e.Effects = DragDropEffects.Link;

            else
                e.Effects = DragDropEffects.None;
        }

        private void ListBox1_Drop(object sender, DragEventArgs e)
        {
            try
            {
                if(!e.Data.GetDataPresent(DataFormats.FileDrop))
                    return;

                Array paths = (Array)e.Data.GetData(DataFormats.FileDrop);

                foreach(string item in paths)
                {
                    if(Directory.Exists(item))
                    {
                        // 处理文件夹：直接搜索所有DWG文件
                        DirectoryInfo root = new DirectoryInfo(item);
                        FileInfo[] xlsxFiles = root.GetFiles("*.xlsx", SearchOption.AllDirectories);

                        foreach(var fileInfo in xlsxFiles)
                        {
                            AddUniqueItem(listBox1, fileInfo.FullName);
                        }
                    } else if(File.Exists(item) && IsXlsxFile(item))
                    {
                        AddUniqueItem(listBox1, item);
                    }
                }
            } catch(Exception ex)
            {
                MessageBox.Show(
                    $"处理文件时出错: {ex.Message}",
                    "错误",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
            }
        }

        private void Button3_Click(object sender, RoutedEventArgs e)
        {
            ExcelPackage.License.SetNonCommercialPersonal("zhwang");

            foreach (var fileName in listBox1.Items.Cast<string>())
            {

                using (var package = new ExcelPackage(new FileInfo(fileName)))
                {

                    if (rbB.IsChecked == true)
                    {
                        foreach (ExcelWorksheet worksheet in package.Workbook.Worksheets)
                        {

                            // 遍历工作表的所有单元格
                            foreach (var cell in worksheet.Cells)
                            {
                                // 检查单元格是否包含公式
                                if (cell.Formula != null && cell.Formula != "")
                                {
                                    // 获取公式计算后的值
                                    var cellValue = cell.Value;

                                    // 清除公式但保留值
                                    cell.Formula = null;

                                    cell.Value = cellValue;
                                }
                            }


                        }

                    }
                    else
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

                        // 遍历工作表的所有单元格
                        foreach (var cell in worksheet.Cells)
                        {
                            // 检查单元格是否包含公式
                            if (cell.Formula != null && cell.Formula != "")
                            {
                                // 获取公式计算后的值
                                var cellValue = cell.Value;

                                // 清除公式但保留值
                                cell.Formula = null;

                                cell.Value = cellValue;
                            }
                        }
                    }
                    string obFileName = string.Empty;

                    if (rbAddHouZhui.IsChecked==true)
                    {
                        if (houzhui.Text.Trim().Length>=1)
                        {
                            obFileName = InsertBeforeExtension(fileName, houzhui.Text.Trim());
                        }
                        else
                        {
                            MessageBox.Show("文件后缀长度要大于等于1个字符");
                            return;
                        }
                        
                    }
                    if (saveToDirectory.IsChecked==true)
                    {
                        if (houzhui.Text.Trim().Length >= 1)
                        {
                            obFileName = System.IO.Path.GetFileName(fileName);

                            obFileName= InsertBeforeExtension(obFileName, houzhui.Text.Trim());

                            obFileName = System.IO.Path.Combine(textbox2.Text.Trim(), obFileName);
                            
                        }
                        else
                        {
                            MessageBox.Show("文件后缀长度要大于等于1个字符");
                            return;
                        }
 
                    }




                   

                    // 保存文件
                    package.SaveAs(new FileInfo(obFileName));

                    MessageBox.Show("everything is ok!");
                }


            }

        }
        
        /// <summary>
        /// 在文件后缀前插入指定字符串
        /// </summary>
        /// <param name="fileName">完整文件名（如：document.xlsx）</param>
        /// <param name="insertString">要插入的字符串</param>
        /// <returns>插入后的新文件名</returns>
        public static string InsertBeforeExtension(string fileName, string insertString)
        {
            // 获取文件扩展名（包括点号）
            string extension = System.IO.Path.GetExtension(fileName);

            string newFileName = string.Empty;

            int lastSlashIndex = fileName.LastIndexOf(extension);

            if (lastSlashIndex != -1)
            {
                newFileName = fileName.Substring(0, lastSlashIndex) + insertString + extension;

            }

            return newFileName;
        }

        private void Button4_Click(object sender, RoutedEventArgs e)
        {
            while (listBox1.SelectedItems.Count > 0)
            {
                listBox1.Items.Remove(listBox1.SelectedItems[0]); // 总是移除第一个选中项
            }
        }

        private void SaveToDirectory_Checked(object sender, RoutedEventArgs e)
        {
           System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();

           

            bool b = false;

            while(b==false)
            {
                System.Windows.Forms.DialogResult dialogResult = folderBrowserDialog.ShowDialog();

                if (dialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    obFolder = folderBrowserDialog.SelectedPath;

                    if (System.IO.Directory.Exists(obFolder) == false)
                    {
                        return;
                    }
                    else
                    {
                        b = true;

                        textbox2.Text = obFolder;

                        textbox2.Visibility = Visibility.Visible;
                    }
                }
                else
                {
                    MessageBox.Show("没有选择有效的存储路径。请重新选择有效路径");
                  
                }

            }
            
        }

        private void RbAddHouZhui_Checked(object sender, RoutedEventArgs e)
        {
   
        }
    }
}
